package com.banciyuan.bcywebview.biz.topic;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpecialApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Special;

/**
 * Created by squall on 2017/7/18.
 */

public class TopicDetailListFragment extends BaseLazyContainerFragment {

    private PullToRefreshListView refreshListView;
    private ListView mListView;
    private TopicDetailListAdapter adapter;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private RequestQueue queue;
    private List<Special> slist = new ArrayList<>();
    private int page = 1;
    private boolean isEnd = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.top_fragment_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initUi(View viewroot) {
        refreshListView = (PullToRefreshListView) viewroot.findViewById(R.id.top_refresh_lv);
        mListView = refreshListView.getRefreshableView();
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        String url = HttpUtils.BASE_URL + SpecialApi.getSpecials();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray data = jsonObject.getJSONArray("data");
                        Gson gson = new Gson();
                        List<Special> temp = gson.fromJson(data.toString(), new TypeToken<List<Special>>() {
                        }.getType());
                        if (!temp.isEmpty()) {
                            dealJson(temp);
                        } else {
                            isEnd = true;
                        }

                    } catch (JSONException e) {
                        mProgressbarHelper.onFailed();
                        refreshListView.onRefreshComplete();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                refreshListView.onRefreshComplete();
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void dealJson(List<Special> temp) {
        if (page == 1) {
            slist.clear();
        }
        slist.addAll(temp);
        if (null != adapter) {
            adapter.notifyDataSetChanged();
        } else {
            adapter = new TopicDetailListAdapter(slist, getActivity());
            refreshListView.setAdapter(adapter);
        }
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
        isEnd = false;
    }

    @Override
    protected void initProgressbar(View rootView) {
        mProgressbarView = rootView.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                initData();
            }
        });

        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!isEnd) {
                    page++;
                    initData();
                }
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                gotoUtil.gotoAct(getActivity(), TopicDetailActivity.class, slist.get(i - 1).getSpecial_id());
            }
        });
    }

}
